package com.coder520.sync_learning.demo.balking;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 代表正在编辑的文档类
 *
 * balking设计模式 多线程
 */
public class Document {


    // 如果文档发生了变化，changed会被设置成true
    private boolean changed = false;


    // 一次需要保存的内容，可以理解为内容的缓存
    private List<String> content = new ArrayList<>();


    private final FileWriter writer;

    private static  AutoSaveThread autoSaveThread;

    private Document(String documentPath,String documentName) throws IOException {

        this.writer = new FileWriter(new File(documentPath,documentName),true);

    }

    public static  Document create(String documentPath,String documentName) throws  IOException{
        Document document = new Document(documentPath,documentName);
        autoSaveThread = new AutoSaveThread(document);
        autoSaveThread.start();
        return document;
    }

    public void edit(String content){
        synchronized (this){
            this.content.add(content);
            this.changed = true;
        }
    }

    private void close() throws IOException {
        autoSaveThread.interrupt();
        writer.close();
    }

    public void save() throws IOException {
        synchronized (this){
            // balking 如果文档已经被保存了，则直接返回
            if (!changed){
                return;
            }

            System.out.println(Thread.currentThread() + "execute the save action.");

            for(String cacheLine : content){
                this.writer.write(cacheLine);
                this.writer.write("\r\n");
            }

            this.writer.flush();

            // 将changed 修改为false,表明此刻已经没有新的内容编辑
            this.changed=false;
            this.content.clear();
        }
    }
}
